<template>
  <div class="login">
    <info :ruleForm="contextInfo" @on-behavior="onLogin" ref="infoRef" />
  </div>
</template>

<script lang="ts">
import { reactive, ref, defineComponent, onMounted } from "vue";
import info, { ContextProps } from "../components/ReInfo/index.vue";
// import { login } from "/@/api/user";
import { getAsyncRoutes } from "/@/api/menu";
import { useRoute } from "vue-router";
import { storageLocal } from "/@/utils/storage";
// import { errorMessage, successMessage } from "/@/utils/message";
import NotifMessage from "/@/utils/message/notification";
import { clickEvent } from "/@/utils/func";
import axios from "axios";
import qs from "qs";
import JSEncrypt from "jsencrypt";
import { identifyHowxm } from "howxm-js";
export default defineComponent({
  name: "login",
  components: {
    info
  },
  setup() {
    // const router = useRouter();
    const route = useRoute();
    const infoRef = ref<HTMLElement | null>(null) as any;

    const baseUrl = ref(import.meta.env.VITE_BASE_URL);

    const contextInfo: ContextProps = reactive({
      userName: "",
      passWord: "",
      identify: ""
    });
    onMounted(() => {
      storageLocal.clear();
    });

    const toPage = (info: Object): void => {
      storageLocal.setItem("info", info);
      clickEvent("工程项目管理登录页面", "登录", "普通登录");
      const { redirect } = route.query;
      if (redirect) {
        window.location.href = `${redirect}`;
      } else {
        getAuthMenu();
      }
    };

    const getAuthMenu = async () => {
      const { origin, pathname } = location;
      try {
        const { code, data } = await getAsyncRoutes({});
        if (code === 200) {
          const info = data ?? [];
          storageLocal.setItem("menuTree", info);
          if (info?.length) {
            const projectsIndex = info.findIndex(
              item => item.menuCode === "projects"
            );
            const approvalIndex = info.findIndex(
              item => item.menuCode === "approval"
            );
            if (projectsIndex > -1) {
              window.location.href = `${origin}${pathname}#${info[projectsIndex].menuPath}`;
              window.location.reload();
            } else if (approvalIndex > -1) {
              window.location.href = `${origin}${pathname}#${info[approvalIndex].menuPath}`;
              window.location.reload();
            } else {
              window.location.href = `${origin}${pathname}#/`;
              window.location.reload();
              // router.replace({ path: "/" });
            }
          } else {
            window.location.href = `${origin}${pathname}#/`;
            window.location.reload();
            // router.replace({ path: "/" });
          }
        } else {
          window.location.href = `${origin}${pathname}#/`;
          window.location.reload();
          // router.replace({ path: "/" });
        }
      } catch (err) {
        window.location.href = `${origin}${pathname}#/`;
        window.location.reload();
        // router.replace({ path: "/" });
      }
    };

    // 登录
    const onLogin = async () => {
      const encryptor = new JSEncrypt(); // 创建加密对象实例
      let publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKcbECgXDZ/989X8TuAFfQpDUi0i5n7EZpwGvbETXLXtHunS1SPDbLlrlYjSaF9bAAdf5SsPtkOyoQJALMw24AkCAwEAAQ==`;

      // 生产环境的密钥
      if (import.meta.env.VITE_PROJECT_ENV === "pre") {
        publickKey = `MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOoQrxqdDPj7Yafbp+qDnv4XZ+3J9wP7DTT3Lu1vwOsq
      cMW4x5lo54ROu7VMx1m4iaUxj7L/uApoh2klC4muEx8CAwEAAQ==`;
      }
      const publicPassword = `-----BEGIN PUBLIC KEY-----${publickKey}-----END PUBLIC KEY-----`;
      encryptor.setPublicKey(publicPassword); //设置公钥
      console.log("contextInfo", contextInfo);
      let { userName, passWord, loginType, textCode, telephone } = contextInfo;

      let params: any = {
        userName,
        password: passWord
      };
      if (loginType == "mobile") {
        params = {
          userName: telephone,
          password: textCode
        };
      }
      const rsaPassWord = encryptor.encrypt(params.password); // 对内容进行加密
      const transferPassword = btoa(rsaPassWord as string);
      // console.log(rsaPassWord, transferPassword, "rsaPassWord");
      params.password = transferPassword;
      const loginUrl = `${baseUrl.value}/snow-admin/login?${qs.stringify(
        params
      )}`;
      try {
        axios.defaults.headers["loginMethod"] = "PC";
        axios.defaults.headers["loginType"] = loginType;
        const res = await axios.post(loginUrl);
        if (res.status === 200) {
          // 浩客identify 用户身份信息传递
          identifyHowxm({
            uid: res.data.body.data.userName, // 用户唯一ID, 默认字段, 必填，string 类型
            name: res.data.body.data.name // 名称，默认字段，非必填，string 类型
          });
          // successMessage(`${res.data.body.message}`);
          NotifMessage.success(res.data.body.message);
          // console.log(res);
          toPage({
            username: res.data.body.data.userName,
            name: res.data.body.data.name,
            userId: res.data.body.data.userId,
            accessToken: res.data.body.data.token
          });
        }
      } catch (err) {
        // 如果错误就刷新验证码
        infoRef.value.refreshCode();
        if (err?.response?.status === 401) {
          NotifMessage.error("用户名或者密码错误");
          // errorMessage("用户名或者密码错误");
        }
        console.log(err);
      }
    };

    return {
      infoRef,
      contextInfo,
      onLogin,
      // router,
      toPage
    };
  }
});
</script>
